
package com.example.main.Conditional.Conditional_OnBean_MissingBean_OnSingleCandidate;

import java.util.List;

import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnSingleCandidate;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;

@Configuration
public class TestConfig {
    
    @Bean
    @ConditionalOnMissingBean(Test1.class)
    Test1 test1() {
        System.out.println("---------Test1 实例化bean不存在，将Test1注册到容器中---------");
        return new Test1();
    }
    
    @Bean
    @ConditionalOnBean(Test1.class)
    Test2 test2() {
        System.out.println("---------Test1 实例化bean存在，将Test2注册到容器中---------");
        return new Test2();
    }
    
    @Bean
    @ConditionalOnSingleCandidate(Test1.class)
    Test2 test3() {
        System.out.println("---------当指定Bean在容器中只有一个，或者虽然有多个但是指定首选Bean，就注册test3到容器中---------");
        return new Test2();
    }
    
    public class Test1 {
    }
    
    public class Test2 {
    }
    
    public static void main(String[] args) {
        
        // 设置日志级别,去掉我不要的信息
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        List<Logger> loggerList = loggerContext.getLoggerList();
        loggerList.forEach(logger -> {
            logger.setLevel(Level.ERROR);
        });
        
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(TestConfig.class);
        
    }
}